<template>
  <a-card :bordered="false" style="width: 100%">
    <!-- 查询区域 -->
    <search ref="search" :config="searchConfig" :searchOn="queryParam" @getHeight="getHeight" @search="search"/>
    <!-- 操作按钮区域 -->
    <vxe-toolbar size="small" ref="xToolbar">
      <template #buttons>
        <div class="table-operator">
          <a-button v-has="'depart:add'" @click="addOrg">新增</a-button>
          <a-button v-has="'depart:delete'" @click="batchDel">删除</a-button>
          <a-button v-has="'depart:export'" type="primary" @click="downExportXls('depart_report')">导出</a-button>
        </div>
      </template>
    </vxe-toolbar>
    <!-- table区域-begin -->
    <div class="totalView">
      <div class="left">
        <a-input-search v-model="searchOn.orgName" style="margin-bottom: 8px" placeholder="请输入组织名称" enter-button
                        @search="onSearchs"/>
        <div class="tree-right" :style="'height:'+ (pageHeight-seachHeight-196) +'px;'">
          <a-tree
            :auto-expand-parent="autoExpandParent"
            :tree-data="treeData"
            :selectedKeys="[queryParam.parentCode]"
            :checkStrictly="true"
            :replaceFields="{children: 'children', title: 'orgName', key: 'orgCode'}"
            style="width:100%;border: 0px;border: none;outline:none;"
            @select="selectNode"
          >
          </a-tree>
        </div>
      </div>

      <div class="right">
        <vxe-grid
          ref="xGrid"
          size="mini"
          :border="true"
          :resizable="true"
          :showOverflow="true"
          :loading="loading"
          :height="pageHeight-seachHeight-132"
          :align="left"
          :columns="columns"
          :data="dataSource"
          :treeConfig="treeConfig"
          @radio-change="radioChangeEvent"
          :radio-config="{ trigger: 'row'}"
        >
          <template #action="{ row }">
            <a v-has="'depart:update'" href="javascript:" @click="handleAdd(3, row )">编辑</a>
            <a-divider type="vertical"/>
            <!--              <a-popconfirm title='确定删除吗?' @confirm='() => handleDelete(row.id)'>-->
            <!--                <a>删除</a>-->
            <!--              </a-popconfirm>-->
            <!--              <a-divider type='vertical' />-->
            <a v-has="'business:log'" href="javascript:" @click='handleBusiness("组织管理",row)'>日志</a>
          </template>

          <template #pager>
            <vxe-pager
              :layouts="['Total', 'PrevJump', 'PrevPage', 'Number', 'NextPage', 'NextJump','Sizes', 'FullJump']"
              :currentPage.sync="ipagination.current"
              :page-size.sync="ipagination.pageSize"
              :total="ipagination.total"
              :pageSizes="ipagination.pageSizeOptions"
              @page-change="handlePageChange">
            </vxe-pager>
          </template>
        </vxe-grid>
      </div>
    </div>
    <!--    parentCode-->
    <!-- table区域-end -->
    <depart-modal ref="departModal" @ok="searchQuery1"></depart-modal>
    <!--    <orgtoUser ref='orgtoUser' @ok='saveUserRelation'></orgtoUser>-->
    <business-log ref="businessLog"></business-log>
  </a-card>

</template>
<script>
import orgtoUser from '@views/dms/orgtoUser'
import DepartModal from '@page-modules/DepartModal'
import { pick } from 'lodash'
import { queryDepartTreeList, searchByKeywords, deleteByDepartId } from '@/api/api'
import { httpAction, deleteAction, getAction, postAction } from '@/api/manage'
import { PageListMixin } from '@/mixins/PageListMixin'
import DepartAuthModal from '@page-modules/DepartAuthModal'
import JTreeTable from '@/components/cn-form/JTreeTable'
import search from '@comp/view/base-crud/search/Search'
import { filterObj } from '@/utils/util'

export default {
  name: 'DepartList',
  mixins: [PageListMixin],
  components: {
    DepartAuthModal,
    DepartModal,
    JTreeTable,
    orgtoUser,
    search
  },
  data() {
    return {
      treeConfig: {
        rowField: 'orgCode',
        parentField: 'parentCode'
      },
      doSearch: 0,
      iExpandedKeys: [],
      loading: false,
      autoExpandParent: true,
      currFlowId: '',
      currFlowName: '',
      disable: true,
      treeData: [],
      visible: false,
      departTree: [],
      rightClickSelectedKey: '',
      rightClickSelectedOrgCode: '',
      hiding: true,
      model: {},
      dropTrigger: '',
      depart: {},
      queryKey: '',
      disableSubmit: false,
      checkedKeys: [],
      selectedKeys: [],
      autoIncr: 1,
      currSelected: {},
      allTreeKeys: [],
      checkStrictly: true,
      form: this.$form.createForm(this),
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      graphDatasource: {
        nodes: [],
        edges: []
      },
      searchConfig: [
        {
          type: 'input',
          name: 'orgCode',
          placeholder: '组织编号'
        },
        {
          type: 'input',
          name: 'orgName',
          placeholder: '组织名称'
        },
        {
          type: 'j-select',
          name: 'orgType',
          dictCode: 'org_type',
          placeholder: '请选择组织类型'
        }
      ],
      // 表头
      columns: [
        { type: 'radio', width: 60, fixed: 'left' },
        {
          title: '组织编号',
          field: 'orgCode',
          width: 160,
          fixed: 'left',
          treeNode: true
        },
        {
          title: '组织名称',
          minWidth: 80,
          field: 'orgName'
        },
        {
          title: '组织类型',
          minWidth: 80,
          field: 'orgType_dictText'
        },
        {
          title: '创建人',
          field: 'createName',
          minWidth: 80
        },
        {
          title: '创建时间',
          field: 'createTime',
          minWidth: 80
        },
        {
          title: '更新人',
          field: 'updateName',
          minWidth: 80
        },
        {
          title: '更新时间',
          field: 'updateTime',
          minWidth: 80
        },
        {
          title: '操作',
          minWidth: 100,
          field: 'action',
          fixed: 'right',
          slots: { default: 'action' }
        }

      ],
      validatorRules: {
        orgName: { rules: [{ required: true, message: '' }] },
        orgCode: { rules: [{ required: true, message: '' }] },
        orgType: { rules: [{ required: true, message: '' }] },
        mobile: { rules: [{ validator: this.validateMobile }] }
      },
      url: {
        list: window._CONFIG['domianURL'] + '/cnOrgController/findOrgListByParentCode',
        // treeUrls: window._CONFIG['domianURL'] + '/cnOrgController/findOrgListByParentCode',
        //组织树
        treeList: window._CONFIG['domianURL'] + '/cnOrgController/findTreeList',
        delete: window._CONFIG['domianURL'] + '/cnOrgController/deleteAllByidOrCode',
        edit: window._CONFIG['domianURL'] + '/cnOrgController/saveOrUpdateEntity',
        deleteBatch: '/cnOrgController/deleteBatch',
        exportXlsUrl: window._CONFIG['domianURL'] + '/CnOrgService/todoExcel',
        sync: window._CONFIG['domianURL'] + '/cnOrgController/oaOrgQuery',
        importExcelUrl: 'sys/sysDepart/importExcel'
      },
      orgCategoryDisabled: false

    }
  },
  computed: {
    importExcelUrl: function () {
      return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`
    },
    tableProps() {
      let _this = this
      return {
        // 列表项是否可选择
        // 配置项见：https://vue.ant.design/components/table-cn/#rowSelection
        rowSelection: {
          type: 'radio',
          selectedRowKeys: _this.selectedRowKeys,
          onChange: (selectedRowKeys) => _this.selectedRowKeys = selectedRowKeys,
          onSelect: function (record, selected, selectedRows, nativeEvent) {
            _this.selectData = record
          }
        }
      }
    }
  },
  methods: {
    modalFormOk() {
      // this.searchOn = ''
      // this.onExpand()
      this.onSearchs()
    },
    onSearchs() {
      this.loadTreeDatas('1')
    },
    // // 加载树数据
    loadTreeDatas(arg) {
      // 加载查询接口
      let datasparams = {}
      if (arg) {
        datasparams = { ...this.searchOn, current: 1 }
      }
      if (!this.url.treeList) {
        this.$message.info('请配置树状接口地址"treeList"')
        return
      }
      postAction(this.url.treeList, datasparams).then(res => {
        console.log(res.result)
        this.treeData = [...res.result.records]
      })
    },
    selectNode(e, e2) {
      this.queryParam.parentCode = e[0]
      this.selectedRowKeys = []
      this.selectionRows = []
      this.loadData(1)
    },
    saveUserRelation(cord) {
      this.loading = true
      let param = {
        userVos: cord.users,
        orgCode: cord.val.orgCode
      }
      postAction(window._CONFIG['domianURL'] + '/cnOrgController/saveUserOrg', { ...param }).then(res => {
        if (!res.success) {
          this.$message.error(res.message)
          return
        }
        this.$message.success('添加成功')
        this.loading = false
      })
    },
    search(queryParam, butType) {
      this.selectedRowKeys = []
      this.selectionRows = []
      this.searchOn = {}
      this.queryParam = queryParam
      this.loadData(1)
    },
    userlist(record, type = 'treeTable', modal = 'orgtoUser') {
      this.$refs[modal].showModal(record)
      return false
    },
    selecttype(value) {
      this.$set(this.queryParam, 'orgType', value)
    },

    searchQuery1() {
      this.doSearch = this.doSearch + 1
      // this.selectNode([0])
      this.loadData()
      this.loadTreeDatas()
      this.selectedRowKeys = []
    },
    searchReset1() {
      this.queryParam = {}
      this.doSearch = this.doSearch + 1
    },
    setThisExpandedKeys(node) {
      if (node.children && node.children.length > 0) {
        this.iExpandedKeys.push(node.orgCode)
        for (let a = 0; a < node.children.length; a++) {
          this.setThisExpandedKeys(node.children[a])
        }
      }
    },
    refresh() {
      this.searchQuery1()
    },
    // 右键操作方法
    rightHandle(node) {
      this.dropTrigger = 'contextmenu'
      console.log(node.node.eventKey)
      this.rightClickSelectedKey = node.node.eventKey
      this.rightClickSelectedOrgCode = node.node.dataRef.orgCode
    },
    onExpand(expandedKeys) {
      console.log('onExpand', expandedKeys)
      // if not set autoExpandParent to false, if children expanded, parent can not collapse.
      // or, you can remove all expanded children keys.
      this.iExpandedKeys = expandedKeys
      this.autoExpandParent = false
    },
    backFlowList() {
      this.$router.back(-1)
    },
    // 右键点击下拉框改变事件
    dropStatus(visible) {
      if (visible == false) {
        this.dropTrigger = ''
      }
    },
    getQueryParams() {
      //获取查询条件
      let sqp = {}
      if (this.superQueryParams) {
        sqp['superQueryParams'] = encodeURI(this.superQueryParams)
        sqp['superQueryMatchType'] = this.superQueryMatchType
      }
      var param = Object.assign(sqp, this.queryParam, this.isorter, this.filters)
      param.field = this.getQueryField()
      param.current = this.ipagination.current
      param.size = this.ipagination.pageSize
      if (this.permflag != undefined && this.permflag != null && this.permflag != '') {
        param.permflag = this.permflag
      }
      return filterObj(param)
    },
    loadData(arg) {
      if (!this.url || !this.url.list) {
        // this.$message.error("请设置url.list属性!")
        return
      }
      //加载数据 若传入参数1则加载第一页的内容
      if (arg === 1) {
        this.ipagination.current = 1
      }
      var params = this.getQueryParams()//查询条件
      console.log(params)
      this.loading = true
      let request = null
      const isNoPagnation = ['getDictByCode'].some(url => new RegExp(`${url}$`).test(this.url.list))
      if (isNoPagnation) {
        request = getAction
      } else {
        request = postAction
      }
      var that = this
      return request(this.url.list, params).then((res) => {
        if (res.success) {
          that.dataSource = res.result.records
          // that.treeData = res.result.records
          if (!isNoPagnation) that.ipagination.total = res.result.total || 0
        } else {
          that.$message.warning(res.message)
        }
        that.loading = false
      })
    },
    batchDel: function () {
      console.log(this.checkedKeys)
      if (this.selectedRowKeys.length <= 0) {
        this.$message.warning('请选择一条记录！')
      } else {
        var ids = ''
        for (var a = 0; a < this.selectedRowKeys.length; a++) {
          ids += this.selectedRowKeys[a] + ','
        }
        var that = this
        this.$confirm({
          title: '确认删除',
          content: '确定要删除所选中的 ' + this.selectedRowKeys.length + ' 条数据，以及子节点数据吗?',
          onOk: function () {
            getAction(that.url.deleteBatch, { ids: ids }).then((res) => {
              if (res.success) {
                that.$message.success(res.message)
                that.searchQuery1()
              } else {
                that.$message.warning(res.message)
              }
            })
          }
        })
      }
    },
    // 触发onSelect事件时,为部门树右侧的form表单赋值
    setValuesToForm(record) {
      if (record.orgType == '1') {
        this.orgCategoryDisabled = true
      } else {
        this.orgCategoryDisabled = false
      }
      this.$nextTick(() => {
        this.form.getFieldDecorator('fax', { initialValue: '' })
        this.form.setFieldsValue(pick(record, Object.keys(record)))
      })
    },
    getCurrSelectedTitle() {
      return !this.currSelected.title ? '' : this.currSelected.title
    },
    onClearSelected() {
      this.hiding = true
      this.checkedKeys = []
      this.currSelected = {}
      this.form.resetFields()
      this.selectedKeys = []
      this.$refs.departAuth.departId = ''
    },
    handleNodeTypeChange(val) {
      this.currSelected.nodeType = val
    },
    notifyTriggerTypeChange(value) {
      this.currSelected.notifyTriggerType = value
    },
    receiptTriggerTypeChange(value) {
      this.currSelected.receiptTriggerType = value
    },
    submitCurrForm() {
      let that = this
      this.form.validateFields((err, values) => {
        if (!err) {
          if (!this.currSelected.id) {
            this.$message.warning('请点击选择要修改部门!')
            return
          }

          let formData = Object.assign(this.currSelected, values)
          console.log('Received values of form: ', formData)
          httpAction(this.url.edit, formData, 'post').then((res) => {
            if (res.success) {
              that.$message.success('保存成功!')
              that.searchQuery1()
            } else {
              that.$message.error(res.message)
            }
          })
        }
      })
    },
    emptyCurrForm() {
      this.form.resetFields()
    },
    nodeSettingFormSubmit() {
      this.form.validateFields((err, values) => {
        if (!err) {
          console.log('Received values of form: ', values)
        }
      })
    },
    openSelect() {
      this.$refs.sysDirectiveModal.show()
    },
    addOrg() {
      // if (this.selectedRowKeys.length > 0) {
      //  this.handleAdd(2)
      // } else {
      this.handleAdd(1)
      // }
    },
    handleAdd(num, row) {
      if (num == 1) {
        this.$refs.departModal.add()
        this.$refs.departModal.title = '新增'
      } else if (num == 2) {
        let key = ''
        if (this.selectedRowKeys.length > 0) {
          key = this.selectionRows[0].orgCode
        } else {
          key = this.queryParam.parentCode
        }
        console.log(key)
        if (!key) {
          this.$message.warning('请先点击选中上级组织！')
          return false
        }
        this.$refs.departModal.add(key)
        this.$refs.departModal.title = '新增'
      } else {
        // if (this.selectedRowKeys.length <= 0) {
        //   this.$message.warning('请先点击选中组织！')
        //   return false
        // }
        // console.log(this.selectionRows[0])
        this.$refs.departModal.addnew(row)
        this.$refs.departModal.title = '编辑'
      }
    },
    // handleDelete() {
    //   var that = this
    //   this.$confirm({
    //     title: '确认删除',
    //     content: '确定要删除此组织以及子节点数据吗?',
    //     onOk: function() {
    //       deleteByDepartId({ orgCode: that.rightClickSelectedKey }).then((resp) => {
    //         if (resp.success) {
    //           //删除成功后，去除已选中中的数据
    //           that.checkedKeys.splice(that.checkedKeys.findIndex(key => key === that.rightClickSelectedKey), 1)
    //           that.$message.success('删除成功!')
    //           that.searchQuery1()
    //           //删除后同步清空右侧基本信息内容
    //           let orgCode = that.form.getFieldValue('orgCode')
    //           if (orgCode && orgCode === that.rightClickSelectedOrgCode) {
    //             that.onClearSelected()
    //           }
    //         } else {
    //           that.$message.warning('删除失败!')
    //         }
    //       })
    //     }
    //   })
    // },
    handleDelete: function (id) {
      if (!this.url.delete) {
        this.$message.error('请设置url.delete属性!')
        return
      }
      var that = this
      getAction(that.url.delete, { id: id }).then((res) => {
        if (res.success) {
          that.$message.success(res.message)
          this.loadData()
        } else {
          that.$message.warning(res.message)
        }
      })
    },
    selectDirectiveOk(record) {
      console.log('选中指令数据', record)
      this.nodeSettingForm.setFieldsValue({ directiveCode: record.directiveCode })
      this.currSelected.sysCode = record.sysCode
    },
    getFlowGraphData(node) {
      this.graphDatasource.nodes.push({
        id: node.id,
        text: node.flowNodeName
      })
      if (node.children.length > 0) {
        for (let a = 0; a < node.children.length; a++) {
          let temp = node.children[a]
          this.graphDatasource.edges.push({
            source: node.id,
            target: temp.id
          })
          this.getFlowGraphData(temp)
        }
      }
    },
    // <!---- author:os_chengtgen -- date:20190827 --  for:切换父子勾选模式 =======------>
    expandAll() {
      this.iExpandedKeys = this.allTreeKeys
    },
    closeAll() {
      this.iExpandedKeys = []
    },
    checkALL() {
      this.checkStriccheckStrictlytly = false
      this.checkedKeys = this.allTreeKeys
    },
    cancelCheckALL() {
      //this.checkedKeys = this.defaultCheckedKeys
      this.checkedKeys = []
    },
    switchCheckStrictly(v) {
      if (v == 1) {
        this.checkStrictly = false
      } else if (v == 2) {
        this.checkStrictly = true
      }
    },
    getAllKeys(node) {
      // console.log('node',node);
      this.allTreeKeys.push(node.orgCode)
      if (node.children && node.children.length > 0) {
        for (let a = 0; a < node.children.length; a++) {
          this.getAllKeys(node.children[a])
        }
      }
    },
    // <!---- author:os_chengtgen -- date:20190827 --  for:切换父子勾选模式 =======------>
    delback(record) {
      let that = this
      deleteByDepartId({ orgCode: record.orgCode }).then((resp) => {
        if (resp.success) {
          //删除成功后，去除已选中中的数据
          that.$message.success('删除成功!')
          //删除后同步清空右侧基本信息内容
          // that.topValue = record.id
          that.doSearch = that.doSearch + 1
        } else {
          that.$message.warning('删除失败!')
        }
      })
    }
  },
  created() {
    this.currFlowId = this.$route.params.id
    this.currFlowName = this.$route.params.name
    this.loadTreeDatas()
    this.$nextTick(() => {
      // 手动将表格和工具栏进行关联
      this.$refs.xGrid.connect(this.$refs.xToolbar)
    })
  }

}
</script>
<style scoped lang="less">
.ant-card-body .table-operator {
  /*margin: 15px;*/
  /*margin-bottom: 11px;*/
}

.anty-form-btn {
  width: 100%;
  text-align: center;
}

.anty-form-btn button {
  margin: 0 5px;
}

.anty-node-layout .ant-layout-header {
  padding-right: 0
}

.header {
  padding: 0 8px;
}

.header button {
  margin: 0 3px
}

.ant-modal-cust-warp {
  height: 100%
}

.ant-modal-cust-warp .ant-modal-body {
  height: calc(100% - 110px) !important;
  overflow-y: auto
}

.ant-modal-cust-warp .ant-modal-content {
  height: 90% !important;
  overflow-y: hidden
}

#app .desktop {
  height: auto !important;
}

.drawer-bootom-button {
  /*position: absolute;*/
  bottom: 0;
  width: 100%;
  border-top: 1px solid #e8e8e8;
  padding: 10px 16px;
  text-align: left;
  left: 0;
  background: #fff;
  border-radius: 0 0 2px 2px;
}

.table-page-search-submitButtons {
  display: block;
  margin-bottom: 0px !important;
  white-space: nowrap;
}

.totalView {
  //margin-top: 8px;
  display: flex;
  flex-direction: row;

  .left {
    border: 1px solid #edeff0;
    min-width: 300px;
    padding: 2px;

    .left-header {
      display: flex;
      justify-content: space-around;

      .left-header-text {
        padding: 5px 0 5px 0;
        width: 100%;
        text-align: center;
        font-size: 18px;
        margin-bottom: 26px;
        background-color: #edeff0;
      }
    }
  }

  .right {
    width: calc(100% - 300px);


  }
}

.tree-right {
  overflow-y: scroll;
}
</style>
